#include "project.h"
#include <iostream>
#include <memory>
#include <type_traits>

static_assert(std::is_base_of<std
::enable_shared_from_this<Album>, Album>::value,
              "Album must inherit from enable_shared_from_this<Album>"
);
int main()
{
    Lcd lcd(LCD_DEV_PATH);
    if(lcd.mmap_start == nullptr || lcd.mmap_start == (int*)MAP_FAILED)
    {
        cout << "LCD设备映射失败" << endl;
        return -1;
    }
    cout << "LCD 映射成功，地址: " << lcd.mmap_start << endl;

    if (!FontManager::getInstance().loadFont("/root/ASCII.Dzk")) 
    {
        std::cerr << "字库加载失败，退出" << std::endl;
        return -1;
    }

    Touch touch(TOUCH_DEV_PATH); // 确保 TOUCH_DEV_PATH 正确

    auto album = make_shared<Album>(&lcd);
    cout << "Album created" << endl;

    if (!album->addPhoto("/root/egp.bmp") || !album->addPhoto("/root/gld.bmp"))
    {
        cerr << "添加图片失败" << endl;
        return -1;
    }

    album->addPhoto("/root/kl.bmp");
    album->addPhoto("/root/lkz.bmp");
    album->addPhoto("/root/mld.bmp");
    album->addPhoto("/root/mm.bmp");
    album->addPhoto("/root/pkq.bmp");
    album->addPhoto("/root/qldn.bmp");

    touch.addObserver(album.get());
    cout << "Observer added" << endl;

    touch.startListening(); // 假设 startListening 不 detach
    cout << "Touch listening started" << endl;

    album->displayPhoto();
    cout << "First photo displayed" << endl;

    atomic<bool> running(true);

    // 使用值捕获或确保作用域安全
    thread time_thread([&]() {
        while (running) {
            // 确保 Lcd 类有 displayTime 方法
            lcd.displayTime();
            this_thread::sleep_for(chrono::milliseconds(500));
        }
    });

    // 主循环
    cout << "系统运行中... 按任意键或 Ctrl+C 退出" << endl;
    try {
        while(running) {
            this_thread::sleep_for(chrono::milliseconds(100));
        }
    } catch (...) {
        running = false;
    }

    // 清理资源
    running = false;
    if (time_thread.joinable()) {
        time_thread.join();
    }

    touch.stopListening(); // 必须调用
    cout << "程序正常退出。" << endl;
    return 0;
}